﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WindowsPhoneHostAgent.UIAutomationServiceReference;
using Microsoft.SmartDevice.Connectivity;

namespace WindowsPhoneHostAgent
{
    public partial class Form1 : Form
    {
        AgentClient AgentClient;
        
        public Form1()
        {
            InitializeComponent();
            AgentClient = new AgentClient();
            AgentClient.Trace += new EventHandler<HostAgentCore.SimpleMessageEventArgs>(AgentClient_Trace);
            AgentClient.ServerRefresh += new EventHandler<TestRunStatusModelArgs>(AgentClient_ServerRefresh);
        }

        void AgentClient_ServerRefresh(object sender, TestRunStatusModelArgs e)
        {
            this.console.AppendText(e.TestRunStatusModel.AgentCommand + "\r\n");
            this.console.ScrollToCaret();

            if (e.TestRunStatusModel.CaseStates.Count() > 0)
            {
                // bind test run status to data grid
                this.testRunDataGrid.DataSource = e.TestRunStatusModel.CaseStates;
            }
        }

        void AgentClient_Trace(object sender, HostAgentCore.SimpleMessageEventArgs e)
        {
            this.console.AppendText(e.Message + "\r\n");
            this.console.ScrollToCaret();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
            AgentClient.ConnectToDevices();
            foreach (var d in AgentClient.Devices)
            {
                this.devicesView.Items.Add(new ListViewItem(d.Name, 0));
            }
            AgentClient.Start();

            
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.devicesView.Items.Clear();
            AgentClient.ConnectToDevices();
            foreach (var d in AgentClient.Devices)
            {
                this.devicesView.Items.Add(new ListViewItem(d.Name, 0));
            }
        }

        void InvokeTrace(string message)
        {
            this.console.AppendText(message + "\r\n");
            this.console.ScrollToCaret();
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            AgentClient.Stop();
        }
    }
}
